package com.example.a2302fx.login

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2302fx.R
import com.example.a2302fx.databinding.ActivityLoginBinding
import com.example.a2302fx.room.AppDBUtils
import com.example.base.mvvm.BaseActivity

@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this){
            if(it.code==200){
                ToastUtils.showLong("登录成功")
                SPUtils.getInstance().put("token",it.data.token)
                //用来实现第三方登录
                SPUtils.getInstance().put("username",it.data.phone)
                SPUtils.getInstance().put("password",binding.etPassword.text.toString())
                //数据库
                AppDBUtils.getDb().getUserDao().insert(it.data)

                ARouter.getInstance().build("/app/MainActivity").navigation()
            }
        }
    }

    override fun initView() {
        binding.login.setOnClickListener {
            //非空检验
            val username = binding.etUsername.text.toString()
            val password = binding.etPassword.text.toString()
            if(username.isEmpty()||password.isEmpty()){
                ToastUtils.showLong("用户名和密码不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(username)){
                ToastUtils.showLong("用户名格式为手机号，请规范填写")
                return@setOnClickListener
            }
            viewModel.login(username,password)
        }
        //点击第三方实现登录
        binding.ivThird.setOnClickListener {
            viewModel.login(SPUtils.getInstance().getString("username"),SPUtils.getInstance().getString("password"))
        }
        binding.tvGoreg.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }
    }

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_login

}